package com.uduemc.biso.node.web.api.controller;

import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.uduemc.biso.core.utils.JsonResult;
import com.uduemc.biso.node.core.common.entities.FormData;
import com.uduemc.biso.node.core.entities.SContainerQuoteForm;
import com.uduemc.biso.node.core.entities.SForm;
import com.uduemc.biso.node.core.entities.SFormInfo;
import com.uduemc.biso.node.core.entities.SSystem;
import com.uduemc.biso.node.web.api.component.RequestHolder;
import com.uduemc.biso.node.web.api.dto.RequestFormInfoDataList;
import com.uduemc.biso.node.web.api.dto.RequestGetFormCompSetup;
import com.uduemc.biso.node.web.api.pojo.ResponseTableInfoForm;
import com.uduemc.biso.node.web.api.service.ContainerService;
import com.uduemc.biso.node.web.api.service.FormService;
import com.uduemc.biso.node.web.api.service.HostSetupService;
import com.uduemc.biso.node.web.api.service.SystemService;
import com.uduemc.biso.node.web.api.service.impl.FormServiceImpl;

import cn.hutool.core.collection.CollUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/api/form")
@Api(tags = "表单管理")
public class FormController {

//	private final static Logger logger = LoggerFactory.getLogger(FormController.class);

	@Resource
	private FormService formServiceImpl;

	@Resource
	private HostSetupService hostSetupServiceImpl;

	@Resource
	private ContainerService containerServiceImpl;

	@Resource
	private RequestHolder requestHolder;

	@Resource
	private SystemService systemServiceImpl;

	@ApiOperation(value = "页面表单数据列表", notes = "设计区域获取表单列表时请求该接口，目前已优化只返回页面表单数据。")
	@PostMapping({ "/infos" })
	public JsonResult infos() throws IOException {
		List<SForm> listSForm = formServiceImpl.getCurrentInfos(1);
		return JsonResult.ok(listSForm);
	}

	@ApiOperation(value = "创建页面表单", notes = "获取页面表单数据列表，之前 /create 保留，新增 /page-form-create 接口与 /create 作用相同。修改返回结果为新创建的表单结构数据，同 /get-form-data")
	@PostMapping({ "/create", "/page-form-create" })
	public JsonResult pageFormCreate(@RequestParam("name") String name) throws IOException {
		// 验证创建表单是否数量限制！
		int form = hostSetupServiceImpl.getForm();
		int usedForm = hostSetupServiceImpl.getUsedForm();
		if (usedForm >= form) {
			return JsonResult.messageError("表单数据已达上限，最多只能 " + form + " 个，需要购买请联系管理人员！");
		}
		FormData formData = formServiceImpl.createForm(name);
		if (formData == null) {
			return JsonResult.assistance();
		}
		return JsonResult.ok(formData);
	}

	@ApiOperation(value = "创建系统表单", notes = "获取系统表单数据列表，返回结果为新创建的表单结构数据，同 /get-form-data")
	@PostMapping({ "/system-form-create" })
	public JsonResult systemFormCreate(@RequestParam("name") String name, @RequestParam(value = "systemId", required = false, defaultValue = "0") long systemId)
			throws IOException {
		SSystem sSystem = null;
		if (systemId > 0) {
			sSystem = systemServiceImpl.getCurrentInfoById(systemId);
			if (sSystem == null) {
				return JsonResult.illegal();
			}
		}
		// 验证创建表单是否数量限制！
		int form = hostSetupServiceImpl.getForm();
		int usedForm = hostSetupServiceImpl.getUsedForm();
		if (usedForm >= form) {
			return JsonResult.messageError("表单数据已达上限，最多只能 " + form + " 个，需要购买请联系管理人员！");
		}
		FormData formData = formServiceImpl.createSystemForm(name, sSystem);
		if (formData == null) {
			return JsonResult.assistance();
		}
		return JsonResult.ok(formData);
	}

	@ApiOperation(value = "页面表单数据列表", notes = "获取页面表单数据列表，之前 /list 保留，新增 /page-form-list 接口与 /list 作用相同。")
	@PostMapping({ "/list", "/page-form-list" })
	public JsonResult pageFormList() throws IOException {
		List<ResponseTableInfoForm> listResponseTableInfoForm = formServiceImpl.responseTableInfoFormByType(FormServiceImpl.PageForm);
		return JsonResult.ok(listResponseTableInfoForm);
	}

	@ApiOperation(value = "系统表单数据列表", notes = "获取系统表单数据列表，新增。返回结果增加 mount 字段：挂载的系统数据列表。")
	@PostMapping("/system-form-list")
	public JsonResult systemFormList() throws IOException {
		List<ResponseTableInfoForm> listResponseTableInfoForm = formServiceImpl.responseTableInfoFormByType(FormServiceImpl.SystemForm);
		return JsonResult.ok(listResponseTableInfoForm);
	}

	@ApiOperation(value = "获取表单结构数据", notes = "通过 formId 获取 单个 formData 数据。兼容页面、系统表单数据。返回结果增加 mount 字段：挂载的系统数据列表。")
	@PostMapping("/get-form-data")
	public JsonResult getFormData(@RequestParam("formId") long formId) throws IOException {
		// 验证创建表单是否数量限制！
		FormData formData = formServiceImpl.getCurrentFormDataByFormId(formId);
		if (formData == null) {
			return JsonResult.illegal();
		}
		return JsonResult.ok(formData);
	}

	@ApiOperation(value = "更新页面表单名", notes = "更新页面表单名。修改原来的数据返回，现只返回更新后的表单结构数据，同 /get-form-data。")
	@PostMapping({ "/update", "/page-form-update" })
	public JsonResult pageFormUpdate(@RequestParam("id") long formId, @RequestParam("name") String name) throws IOException {
		SForm sForm = formServiceImpl.getCurrentInfo(formId);
		if (sForm == null) {
			return JsonResult.illegal();
		}
		sForm.setName(name);
		SForm update = formServiceImpl.update(sForm);
		if (update == null) {
			return JsonResult.assistance();
		}
		return JsonResult.messageSuccess("更新成功！", formServiceImpl.getCurrentFormDataByFormId(update.getId()));
	}

	@ApiOperation(value = "更新系统表单名", notes = "更新系统表单名。返回更新后的表单结构数据，同 /get-form-data。")
	@PostMapping("/system-form-update")
	public JsonResult systemFormUpdate(@RequestParam("id") long formId, @RequestParam("name") String name) throws IOException {
		SForm sForm = formServiceImpl.getCurrentInfo(formId);
		if (sForm == null) {
			return JsonResult.illegal();
		}
		sForm.setName(name);
		SForm update = formServiceImpl.update(sForm);
		if (update == null) {
			return JsonResult.assistance();
		}
		return JsonResult.messageSuccess("更新成功！", formServiceImpl.getCurrentFormDataByFormId(update.getId()));
	}

	@ApiOperation(value = "删除页面表单", notes = "之前 /delete 保留，新增 /page-form-delete 接口与 /delete 作用相同。修改原来的数据返回，现返回删除前的表单结构数据，同 /get-form-data。")
	@PostMapping({ "/delete", "/page-form-delete" })
	public JsonResult pageFormDelete(@RequestParam("formId") long formId) throws IOException {
		SForm data = formServiceImpl.getCurrentInfo(formId);
		if (data == null) {
			return JsonResult.illegal();
		}
		FormData formData = formServiceImpl.getCurrentFormDataByFormId(data.getId());
		if (formData == null) {
			return JsonResult.assistance();
		}
		List<SContainerQuoteForm> listSContainerQuoteForm = containerServiceImpl.getCurrentSContainerQuoteFormByHostFormId(requestHolder.getHost().getId(),
				formId);
		if (CollUtil.isNotEmpty(listSContainerQuoteForm)) {
			return JsonResult.messageError("页面中存在引用该表单，删除页面引用该表单后方可进行删除操作！");
		}
		SForm sForm = formServiceImpl.deleteFormData(data);
		if (sForm == null) {
			return JsonResult.assistance();
		}
		return JsonResult.messageSuccess("删除表单成功！", formData);
	}

	@ApiOperation(value = "删除系统表单", notes = "删除系统表单，重置挂载该表单系统数据的 formId 字段为 0，返回结果为删除前的表单结构数据，同 /get-form-data。")
	@PostMapping({ "/system-form-delete" })
	public JsonResult systemFormDelete(@RequestParam("formId") long formId) throws IOException {
		SForm data = formServiceImpl.getCurrentInfo(formId);
		if (data == null) {
			return JsonResult.illegal();
		}
		FormData formData = formServiceImpl.getCurrentFormDataByFormId(data.getId());
		if (formData == null) {
			return JsonResult.assistance();
		}
		SForm sForm = formServiceImpl.deleteFormData(data);
		if (sForm == null) {
			return JsonResult.assistance();
		}
		return JsonResult.messageSuccess("删除表单成功！", formData);
	}

	@ApiOperation(value = "获取页面表单提交数据", notes = "获取前台用户提交到表单的数据，之前 /info-list 保留，新增 /page-info-list 接口与 /info-list 作用相同。")
	@PostMapping({ "/info-list", "/page-info-list" })
	public JsonResult pageInfoList(@RequestBody RequestFormInfoDataList requestFormInfoDataList) throws IOException {
		SForm sForm = formServiceImpl.getCurrentInfo(requestFormInfoDataList.getFormId());
		if (sForm == null) {
			return JsonResult.illegal();
		}
		return JsonResult.ok(formServiceImpl.getPageInfoFormInfoDataByQuery(requestFormInfoDataList));
	}

	@ApiOperation(value = "获取系统表单提交数据的系统内容名称列表", notes = "获取的数据主要用于对系统表单提交数据的查询工作。对应 /system-info-list 接口参数中的 systemName 字段。")
	@ApiImplicitParams({ @ApiImplicitParam(name = "formId", value = "表单的数据ID", required = true),
			@ApiImplicitParam(name = "systemNameSearch", value = "模糊查询内容，为空则不过滤，为全部检索结果。默认为空！") })
	@PostMapping("/system-form-system-name-list")
	public JsonResult systemFormSystemNameList(@RequestParam("formId") long formId,
			@RequestParam(value = "systemNameSearch", required = false, defaultValue = "") String systemNameSearch) throws IOException {
		SForm sForm = formServiceImpl.getCurrentInfo(formId);
		if (sForm == null) {
			return JsonResult.illegal();
		}
		return JsonResult.ok(formServiceImpl.formInfoSystemName(formId, systemNameSearch));
	}

	@ApiOperation(value = "获取系统表单提交数据的系统名称列表", notes = "获取的数据主要用于对系统表单提交数据的查询工作。对应 /system-info-list 接口参数中的 systemItemName 字段。")
	@ApiImplicitParams({ @ApiImplicitParam(name = "formId", value = "表单的数据ID", required = true),
			@ApiImplicitParam(name = "systemName", value = "查询系统的名称，通过 /system-form-system-name-list 接口中返回的结果作为该参数。", required = true),
			@ApiImplicitParam(name = "systemItemNameSearch", value = "模糊查询内容，为空则不过滤，为全部检索结果。默认为空！") })
	@PostMapping("/system-form-system-item-name-list")
	public JsonResult systemFormSystemItemNameList(@RequestParam("formId") long formId, @RequestParam("systemName") String systemName,
			@RequestParam(value = "systemItemNameSearch", required = false, defaultValue = "") String systemItemNameSearch) throws IOException {
		SForm sForm = formServiceImpl.getCurrentInfo(formId);
		if (sForm == null) {
			return JsonResult.illegal();
		}
		return JsonResult.ok(formServiceImpl.formInfoSystemItemName(formId, systemName, systemItemNameSearch));
	}

	@ApiOperation(value = "获取系统表单提交数据", notes = "获取前台用户提交到表单的数据，新增 systemName、systemItemName 两个针对系统表单提交数据的过滤条件，默认两项均为0")
	@PostMapping("/system-info-list")
	public JsonResult systemInfoList(@RequestBody RequestFormInfoDataList requestFormInfoDataList) throws IOException {
		SForm sForm = formServiceImpl.getCurrentInfo(requestFormInfoDataList.getFormId());
		if (sForm == null) {
			return JsonResult.illegal();
		}
		return JsonResult.ok(formServiceImpl.getPageInfoFormInfoDataByQuery(requestFormInfoDataList));
	}

	@ApiOperation(value = "删除页面表单提交数据", notes = "删除页面表单提交数据。之前 /info-delete 保留，新增 /page-info-delete 接口与 /info-delete 作用相同。")
	@PostMapping({ "/info-delete", "/page-info-delete" })
	public JsonResult pageInfoDelete(@RequestParam("formInfoId") long formInfoId) throws IOException {
		SFormInfo sFormInfo = formServiceImpl.getCurrentSFormInfoById(formInfoId);
		if (sFormInfo == null) {
			return JsonResult.illegal();
		}
		SFormInfo deleteFormInfo = formServiceImpl.deleteFormInfo(sFormInfo);
		if (deleteFormInfo == null) {
			return JsonResult.assistance();
		}
		return JsonResult.messageSuccess("删除表单提交数据成功！", deleteFormInfo);
	}

	@ApiOperation(value = "删除系统表单提交数据", notes = "删除系统表单提交数据。")
	@PostMapping("/system-info-delete")
	public JsonResult systemInfoDelete(@RequestParam("formInfoId") long formInfoId) throws IOException {
		SFormInfo sFormInfo = formServiceImpl.getCurrentSFormInfoById(formInfoId);
		if (sFormInfo == null) {
			return JsonResult.illegal();
		}
		SFormInfo deleteFormInfo = formServiceImpl.deleteFormInfo(sFormInfo);
		if (deleteFormInfo == null) {
			return JsonResult.assistance();
		}
		return JsonResult.messageSuccess("删除表单提交数据成功！", deleteFormInfo);
	}

	@ApiOperation(value = "挂载系统表单到系统", notes = "可以挂载多个系统，但是只能是具有留言功能且未挂载表单的系统。")
	@ApiImplicitParams({ @ApiImplicitParam(name = "formId", value = "表单的数据ID", required = true),
			@ApiImplicitParam(name = "systemIds", value = "绑定的系统数据ID，多个系统ID使用英文逗号分隔 [,]。", required = true) })
	@PostMapping("/mount-to-systems")
	public JsonResult mountToSystems(@RequestParam("formId") long formId, @RequestParam("systemIds") String systemIds) throws IOException {
		return formServiceImpl.mountSystem(formId, systemIds);
	}

	@ApiOperation(value = "获取表单组件文本内容", notes = "")
	@ApiImplicitParams({ @ApiImplicitParam(name = "formId", value = "表单的数据ID", required = true) })
	@PostMapping("/get-form-comp-setup")
	public JsonResult getFormCompSetup(@RequestParam("formId") long formId) throws IOException {
		SForm sForm = formServiceImpl.getCurrentInfo(formId);
		if (sForm == null) {
			return JsonResult.illegal();
		}
		return JsonResult.ok(formServiceImpl.getgetFormCompSetup(sForm));
	}

	@ApiOperation(value = "保存表单组件文本内容", notes = "")
	@PostMapping("/save-form-comp-setup")
	public JsonResult saveFormCompSetup(@RequestBody RequestGetFormCompSetup getFormCompSetup) throws IOException {
		return formServiceImpl.saveFormCompSetup(getFormCompSetup);
	}
}
